package com.kgc.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kgc.dao.TbContentMapper;
import com.kgc.entity.TbContent;
import com.kgc.entity.TbContentExample;
import com.kgc.jedis.JedisClient;
import com.kgc.service.TbContentService;
import com.kgc.utils.Ad;
import com.kgc.utils.JsonUtils;
import com.kgc.utils.ResultTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;
@Service
public class TbContentServiceImpl implements TbContentService {
    @Autowired
    private TbContentMapper tbContentMapper;
    @Autowired
    private JedisClient jedisClient;
    @Value("${ad1}")
    private String ad1;
    @Override
    public ResultTable findAll(int page,int pageSize) {
        ResultTable resultTable = new ResultTable();
        PageHelper.startPage(page,pageSize);
        TbContentExample example =new TbContentExample();
        List<TbContent> list = tbContentMapper.selectByExample(example);
        PageInfo<TbContent> pageInfo = new PageInfo<>(list);
        resultTable.setCount(pageInfo.getTotal());
        resultTable.setCode(0);
        resultTable.setData(pageInfo.getList());
        resultTable.setMsg("ojbk");
        return resultTable;
    }

    @Override
    public List<Ad> findAllAd(Long id) {
        String jsonString="";
        List<TbContent> list=null;
        //1.判断key=ad1 在redis中是否存在
        if(jedisClient.exists(ad1)){//为true表示redis中存放缓存的内容
            jsonString=jedisClient.get(ad1);//从redis中取缓的json对象
            // JsonUtils.jsonToPojo(jsonString,TbContent.class);
            list= JsonUtils.jsonToList(jsonString,TbContent.class);
        }else{//不存在
            System.out.println("开始访问数据库.tb....");
            TbContentExample example=new TbContentExample();
            TbContentExample.Criteria criteria = example.createCriteria();
            criteria.andCategoryIdEqualTo(id);
            list= tbContentMapper.selectByExample(example);
            System.out.println("访问数据库结束.....");
            //将List集合转换成json字符串
            jsonString=JsonUtils.objectToJson(list);
            jedisClient.set(ad1,jsonString);
            jedisClient.expire("ad1",60*60*24);
        }
        List<Ad> listAd=new ArrayList<>();
        for (TbContent t:list){
            Ad ad = new Ad();
            ad.setSrcB(t.getPic());
            ad.setSrc(t.getPic2());
            ad.setHref(t.getUrl());
            ad.setAlt("嘿嘿");
            listAd.add(ad);
        }
        return listAd;
    }
}
